#pragma once
#include <iostream>
#include "Lock.hpp"
#include <string>
#include <filesystem>
#include <fstream>
#include <unistd.h>
#include <sys/types.h>
const std::string gsep = "\r\n";
class LogStrategy
{
public:
    LogStrategy()
    {
    }
    ~LogStrategy()
    {
    }
    virtual void SyncLog(std::string messager);
};

class ConsoleLogStrategy : public LogStrategy
{
public:
    ConsoleLogStrategy()
    {
    }
    ~ConsoleLogStrategy()
    {
    }
    void SyncLog(std::string messager) override
    {
        LockGuard lock(_mutex);
        std::cout << messager << std::endl;
    }

private:
    Mutex _mutex;
};

const std::string defaultpath = "./log";
const std::string defaultfile = "my.log";
//向指定的日志文件中写入，默认为my.log
class FileLogStrategy : public LogStrategy
{
public:
    FileLogStrategy(std::string path=defaultpath, std::string file=defaultfile)
        : _file(file), _path(path)
    {
        _file_name += _path + (path.back() == '/' ? "" : "/") + _file;
        if (std::filesystem::exists(_path))
        {
            return;
        }
        else
        {
            try
            {
                std::filesystem::create_directories(_path);
            }
            catch (std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << '\n';
            }
        }
    }
    ~FileLogStrategy()
    {
    }
    void SyncLog(std::string messager) override
    {
        LockGuard lock(_mutex);
        std::ofstream out(_file_name, std::ios::app);
        out << messager << gsep;
        out.close();
    }

private:
    std::string _file;
    std::string _path;
    std::string _file_name;
    Mutex _mutex;
};

enum class LEVEL
{
    DEBUG,
    INFO,
    WARNING,
    ERROR,
    FATAL
};
std::string GetTime()
{
    time_t curr = time(nullptr);
    struct tm curr_tm;
    localtime_r(&curr, &curr_tm);
    char timebuffer[128];
    snprintf(timebuffer, sizeof(timebuffer), "%4d-%02d-%02d %02d:%02d:%02d",
             curr_tm.tm_year + 1900,
             curr_tm.tm_mon + 1,
             curr_tm.tm_mday,
             curr_tm.tm_hour,
             curr_tm.tm_min,
             curr_tm.tm_sec);
    return timebuffer;
}
std::string GetLogLevel(LEVEL level)
{
    switch (level)
    {
    case LEVEL::DEBUG:
        return "DEBUG";
    case LEVEL::INFO:
        return "INFO";
    case LEVEL::WARNING:
        return "WARNING";
    case LEVEL::ERROR:
        return "ERROR";
    case LEVEL::FATAL:
        return "FATAL";
    default:
        break;
    }
}
class Logger
{
public:
    Logger()
    {
        _fflush_strategy = std::make_unique<FileLogStrategy>();
    }

    class LogMessager
    {
    public:
    //这里的文件表示当前使用日志功能的文件：
        LogMessager(LEVEL level, std::string file, int line, Logger &logger)
            : _time(GetTime()), _level(GetLogLevel(level)), _id(getpid()), _file(file), _line(line), _logger(logger)
        {
            std::stringstream ss;
            ss << "[" << _time << "] "
               << "[" << _level << "] "
               << "[" << _id << "] "
               << "[" << _file << "] "
               << "[" << _line << "] "
               << "- ";
            _log_info = ss.str();
        }
        ~LogMessager()
        {
            _logger._fflush_strategy->SyncLog(_log_info);
        }
        LogMessager &operator<<(const std::string info)
        {
            _log_info += info;
            return *this;
        }

    private:
        std::string _time;
        std::string _level;
        pid_t _id;
        std::string _file;
        int _line;

        Logger &_logger;
        std::string _log_info;
        Mutex _mutex;
    };

    LogMessager operator()(LEVEL level, std::string file, int line)
    {
        return LogMessager(level, file, line, *this);
    }
    ~Logger()
    {
    }

private:
    std::unique_ptr<LogStrategy> _fflush_strategy;
};

// 全局日志对象
Logger logger;

// 使用宏，简化用户操作，获取文件名和行号
#define LOG(level) logger(level, __FILE__, __LINE__)
#define Enable_Console_Log_Strategy() logger.EnableConsoleLogStrategy()
#define Enable_File_Log_Strategy() logger.EnableFileLogStrategy()